package com.mywang.weitravel.modules.addfind;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.broadcast.BroadcastAction;
import com.luck.picture.lib.broadcast.BroadcastManager;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureParameterStyle;
import com.mywang.weitravel.R;
import com.mywang.weitravel.adapter.AddFindAdapter;
import com.mywang.weitravel.base.BaseFragment;
import com.mywang.weitravel.modules.image.GlideImageEngine;
import com.mywang.weitravel.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

import static android.app.Activity.RESULT_OK;

/**
 * Created by wangmingyun on 2019/12/10.
 */
public class AddFindFragment extends BaseFragment<AddFindPresenter> implements AddFindContract.View, AddFindAdapter.OnAddListener {

    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.rt_info)
    EditText rtInfo;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.rv_pics)
    RecyclerView rvPics;
    @BindView(R.id.btn_publish)
    Button btnPublish;

    private AddFindAdapter addFindAdapter;
    private ArrayList<LocalMedia> selectPhotos = new ArrayList<>();
    private PictureParameterStyle parameterStyle = new PictureParameterStyle();
    private BroadcastReceiver photoPreviewChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                int removePosition = bundle.getInt(PictureConfig.EXTRA_PREVIEW_DELETE_POSITION);
                selectPhotos.remove(removePosition);
                addFindAdapter.setList(convertPhotoList(selectPhotos, false));
            }
        }
    };

    @Override
    protected AddFindPresenter initPresenter() {
        return new AddFindPresenter(this);
    }

    @Override
    protected int getFragmentLayoutID() {
        return R.layout.fragment_add_find;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        tvTitle.setText("发布");
        addFindAdapter = new AddFindAdapter(mActivity, this);
        addFindAdapter.addData("add");
        rvPics.setAdapter(addFindAdapter);
        rvPics.setLayoutManager(new GridLayoutManager(mActivity, 4));
        initSelectStyle();
        if (getActivity() != null) {
            BroadcastManager.getInstance(getActivity()).registerReceiver(photoPreviewChangeReceiver, BroadcastAction.ACTION_DELETE_PREVIEW_POSITION);
        }

    }


    private void initSelectStyle() {
        if (getActivity() != null) {
            parameterStyle.pictureStatusBarColor = ContextCompat.getColor(getActivity(), R.color.color_00f19d);
            parameterStyle.pictureTitleBarBackgroundColor = ContextCompat.getColor(getActivity(), R.color.color_00f19d);
            parameterStyle.picturePreviewTextColor = ContextCompat.getColor(getActivity(), R.color.color_00f19d);
            parameterStyle.pictureCompleteTextColor = ContextCompat.getColor(getActivity(), R.color.color_00f19d);
            parameterStyle.pictureLeftBackIcon = R.mipmap.icon_left_back_white;
            parameterStyle.pictureExternalPreviewGonePreviewDelete = true;
            parameterStyle.isOpenCompletedNumStyle = true;
        }
    }

    @OnTextChanged(value = R.id.rt_info, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void onAfterTextChange(Editable editable) {
        tvNum.setText(String.format("%s/%s", editable.toString().length(), "500"));
    }

    @OnClick({R.id.iv_title_back, R.id.btn_publish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.btn_publish:
                if (check()) {
                    mPresenter.uploadPhotos(convertPhotoList(selectPhotos, true));
                }
                break;
        }
    }

    private boolean check() {
        if (TextUtils.isEmpty(etTitle.getText().toString().trim())) {
            ToastUtils.showShort("请输入标题");
            return false;
        }
        if (TextUtils.isEmpty(rtInfo.getText().toString().trim())) {
            ToastUtils.showShort("请输入内容");
            return false;
        }
        if (selectPhotos.isEmpty()) {
            ToastUtils.showShort("请至少选择一张图片");
            return false;
        }
        return true;
    }

    @Override
    public void addPic() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .setPictureStyle(parameterStyle)
                .loadImageEngine(GlideImageEngine.getInstance())
                .maxSelectNum(4)
                .selectionMedia(selectPhotos)
                .compress(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    public void preview(int position) {
        PictureSelector.create(this)
                .setPictureStyle(parameterStyle)
                .isNotPreviewDownload(true)
                .loadImageEngine(GlideImageEngine.getInstance())
                .openExternalPreview(position, selectPhotos);
    }

    @Override
    public void onDestroyView() {
        if (getActivity() != null) {
            BroadcastManager.getInstance(getActivity()).unregisterReceiver(photoPreviewChangeReceiver);
        }
        super.onDestroyView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    selectPhotos.clear();
                    selectPhotos.addAll(selectList);
                    addFindAdapter.setList(convertPhotoList(selectList, false));
                    break;
            }
        }
    }

    private ArrayList<String> convertPhotoList(List<LocalMedia> selectList, boolean isCompress) {
        ArrayList<String> photos = new ArrayList<>();
        for (LocalMedia media : selectList) {
            if (isCompress) {
                photos.add(media.getCompressPath());
                LogUtil.e(media.getCompressPath());
            } else {
                photos.add(media.getPath());
            }
        }
        return photos;
    }

    @Override
    public void uploadPhotoSuccessful(List<String> src) {
        mPresenter.publishDiscovery(etTitle.getText().toString(), rtInfo.getText().toString(), src);
    }

    @Override
    public void publishSuccessful() {
        ToastUtils.showShort("发布成功");
        finish();
    }
}
